package com.tg.app.view.recyclerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.tg.app.R;

public class MessageDecoration extends RecyclerView.ItemDecoration {
    /**
     * 分割线缩进值
     */
    private int mPaddingLeft;
    private int mPaddingRight;
    private Paint mPaint;
    private int mDividerHeight = 2;
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    private Context mConext;
    public MessageDecoration(Context context,int dividerColor){
        mConext  = context;
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(dividerColor);
        mPaint.setStyle(Paint.Style.FILL);
        mPaddingLeft = (int) context.getResources().getDimension(R.dimen.message_decrotation_left);
        mPaddingRight = (int) context.getResources().getDimension(R.dimen.message_decrotation_right);

    }

    @Override
    public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent) {
        c.drawColor(mConext.getResources().getColor(R.color.transparent));
        onDrawV(c,parent);
    }

    //由于Divider也有宽高，每一个Item需要向下或者向右偏移
    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
            outRect.set(0, 0, 0, mDividerHeight);
    }
    private void onDrawV(@NonNull Canvas c, @NonNull RecyclerView parent){
         int left = parent.getPaddingLeft();
         int right = parent.getWidth() - parent.getPaddingRight();

         int childCount = parent.getChildCount();
        //最后一个item不画分割线
        for (int i = 0; i < childCount - 1; i++) {
             View child = parent.getChildAt(i);
             RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
             int top = child.getBottom() + params.bottomMargin;
             int bottom = top + mDividerHeight;
            if (mPaint!=null){
                c.drawRect(left + mPaddingLeft, top, right - mPaddingRight, bottom, mPaint);
            }
        }
    }
}
